package com.han.hotelplat.cms.controller.task;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyuncs.exceptions.ClientException;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.ResponseWrapTo.CodeType;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AppEmployyePushUtil;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.DateUtil;
import com.han.hotelplat.comm.utils.HssfUtil;
import com.han.hotelplat.comm.utils.ListSortUtil;
import com.han.hotelplat.comm.utils.MsgHelp;
import com.han.hotelplat.comm.utils.RequestUtil;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.manager.LogManager;
import com.han.hotelplat.model.TaskLogModel;
import com.han.hotelplat.pojo.childtask.Childtask;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.emtask.Emtask;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.log.Logger;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.pojo.sysuserhotel.SysUserHotel;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.employee.EmployeeService;
import com.han.hotelplat.service.emtask.EmTaskService;
import com.han.hotelplat.service.hotel.HotelService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;
import com.han.hotelplat.service.systemuser.SystemuserService;
import com.han.hotelplat.service.sysuserhotel.SysUserHotelService;
import com.han.hotelplat.service.task.TaskService;

@Controller
@RequestMapping("/cms/task")
public class CMSTaskController {
	@Autowired
	private TaskService taskService;
	@Autowired
	private HotelService hotelService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private EmTaskService emTaskService;
	@Autowired
	private LogManager logManager;
	@Autowired
	private HotelmanagerService hotelmanagerService;
	@Autowired
	private ChildTaskService childTaskService;
	@Autowired
	private SystemuserService systemuserService;
	@Autowired
	private SysUserHotelService sysUserHotelService;
	
	/**
	 * form表单提交 Date类型数据绑定 <功能详细描述>
	 * 
	 * @param binder
	 * @see [类、类#方法、类#成员]
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		//实现表单中的字符串自动转换为Date或者Timestamp 类型。
		//http://www.micmiu.com/j2ee/spring/springmvc-binding-date/
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		//binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(dateFormat, true));
	}
	
	/**
	 * 获取对应考勤的房量按照房型统计
		 * @description	
		 * @author  han1088
		 * @param taskId
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updateTaskState", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String updateTaskState(String taskId, Integer state){
		taskService.updateTaskState(taskId,state);
		return new ResponseWrapTo(CodeType.success, "数据修改成功", null).toJson();
	}
	
	/**
	 * 获取对应考勤的房量按照房型统计
		 * @description	
		 * @author  han1088
		 * @param taskId
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getRoomCountGroupRoomType", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getRoomCountGroupRoomType(String taskId){
		JSONArray data = taskService.getRoomCountGroupRoomType(taskId);
		return new ResponseWrapTo(CodeType.success, "数据获取成功", data).toJson();
	}
	
	/**
	 * 获取任务考勤详情按照日期分类
		 * @description	
		 * @author  han1088
		 * @param taskid
		 * @param taskid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskRoomCountGroupByDate", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskRoomCountGroupByDate(String taskid, String emid){
		//考勤记录
		List<Childtask> roomcountli = childTaskService.getTaskRoomCountGroupByDate(taskid,emid);
		return new ResponseWrapTo(CodeType.success, "数据获取成功", roomcountli).toJson();
	}
	
	
	/**
	 * 获取任务考勤详情按照帮工分类
		 * @description	
		 * @author  han1088
		 * @param taskid
		 * @param taskid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskRoomCountGroupByEm", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskRoomCountGroupByEm(String taskid, String date){
		//考勤记录
		List<Childtask> roomcountli = childTaskService.getTaskRoomCountGroupByEm(taskid,date);
		return new ResponseWrapTo(CodeType.success, "数据获取成功", roomcountli).toJson();
	}
	
	/**
	 * 
		 * @description	确认考勤判断余额是否充足
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "authTaskAttendance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String authTaskAttendance(String childtaskids, Integer hotelId){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		if(user == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Map<String, Object> data = childTaskService.authTaskAttendance(childtaskids, 
				hotelId);
		int code = (int) data.get("code");
				
		//data.remove("code");
		return new ResponseWrapTo(code, "",data).toJson();
	}
	
	/**
	 * 获取对应日期的所有帮工考勤详情
		 * @description	
		 * @author  han1088
		 * @param taskId
		 * @param date
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getChildTaskDetailByDate", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public String getChildTaskDetailDate(String taskId,String date){
		List<Childtask> ctli = childTaskService.getEmChildTaskDetail(taskId,date);
		return new ResponseWrapTo(CodeType.success, "数据获取成功", ctli).toJson();
	}
	
	/**
	 * 获取指定帮工的考勤详情
		 * @description	
		 * @author  han1088
		 * @param taskId
		 * @param date
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getChildTaskDetailByEmId", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public String getChildTaskDetailByEmId(String taskId,String emId){
		Map<String, Object> data = childTaskService.getEmTaskAttendance(taskId, emId,null);
		return  new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = "exportTaskDetailExcel", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public void exportTaskDetailExcel(HttpServletResponse resp,HttpServletRequest req, String taskid){
		
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Task t = taskService.getHotelTaskDteail(taskid);
		//记录导出日志
		String host = RequestUtil.getRequest().getRemoteHost();
		Logger logger = new Logger(new Date(), user.getUserid(), host, user.getRealname());
		String context = "导出任务";
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_EXPORT);
		tlm.setTaskid(t.getTaskid());
		logManager.creatTaskLog(tlm, logger);
		
		List<Emtask> list = emTaskService.getEmTaskByTakid(taskid);
		List<String> datelist = new ArrayList<String>();
		int days = DateUtil.daysDistance(t.getStarttime(), t.getEndtime())+1;
		for(int i=0;i<days;i++){
			Date starttime = DateUtil.addDay(t.getStarttime(), i);
			datelist.add(DateUtil.formatYMD(starttime));
		}
		
		String[] columnNames = new String[3+days];
		columnNames[0]="帮工姓名";
		columnNames[1]="帮工收入";
		columnNames[2]="帮工清洁房量";
		int i=3;
		for(String data : datelist){
			columnNames[i]=data;
			i++;
		}
		
		List<Object[]> datas = new ArrayList<Object[]>();
		for(Emtask em : list){
			Map<String, Object> data = childTaskService.getEmTaskAttendance(taskid, em.getEmid(),null);
			List<Childtask> li = (List<Childtask>) data.get("childtaskList");
			Float sumroomcount = (Float) data.get("sumroomcount");
			String realname = (String) data.get("realname");
			Object[] dataObj = new Object[columnNames.length];
			dataObj[0] = realname;
			dataObj[2] = sumroomcount;
			float sunMoney = 0f;
			for(Childtask ct : li){
				sunMoney += ct.getReward();
			}
			dataObj[1] = sunMoney;
			for(int m = 3;m<columnNames.length;m++){
				String date = columnNames[m];
				float roomCount = 0;
				for(Childtask ct : li){
					if(DateUtil.formatYMD(ct.getCreattime()).equals(date)){
						roomCount = ct.getRoomcount();
						break;
					}
					sunMoney += ct.getReward();
				}
				dataObj[m] = roomCount;
			}
			datas.add(dataObj);
		}
		
		String filename = "任务列表.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			HssfUtil.writeHssf("帮工任务明细", columnNames, datas, filename, resp.getOutputStream());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "editTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String editTask(Task task){
		String host = RequestUtil.getRequest().getRemoteHost();
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Task oldt = taskService.getTaskById(task.getId());
		List<Emtask> emli = emTaskService.getEmTaskByTakid(task.getTaskid());
		if(emli.size()>0){
			return new ResponseWrapTo(-1, "已经有帮工报名不能修改任务了", null).toJson();
		}
		//重置为发布中
		oldt.setState(Constant.TASK_STATE_CREAT);
		oldt.setHotelid(task.getHotelid());
		oldt.setStarttime(task.getStarttime());
		oldt.setEndtime(task.getEndtime());
		oldt.setUsercount(task.getUsercount());
		//oldt.setWelfare(task.getWelfare());
		oldt.setRemark(task.getRemark());
		taskService.update(oldt);
		Task newt = taskService.getTaskById(task.getId());
		
		Logger logger = new Logger(new Date(), user.getUserid(), host,user.getRealname());
		String context = "【修改前】"+getLogContext(oldt);
		context = context +";\n【修改后】"+getLogContext(newt);
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_EDIT);
		tlm.setTaskid(oldt.getTaskid());
		logManager.creatTaskLog(tlm, logger);
		
		return new ResponseWrapTo(0, "任务已经修改了", oldt.getTaskid()).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "openTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String openTask(String taskid){
		String host = RequestUtil.getRequest().getRemoteHost();
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Task t = taskService.getHotelTaskDteail(taskid);
		if(t.getShowapp().intValue() == Constant.APP_SHOW_OPEN){
			return new ResponseWrapTo(CodeType.success, "已设置为客户端可见", null).toJson();
		}
		t.setShowapp(Constant.APP_SHOW_OPEN);
		taskService.update(t);
		Logger logger = new Logger(new Date(), user.getUserid(), host,user.getRealname());
		String context = "设置任务可见";
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_SHOWAPP);
		tlm.setTaskid(t.getTaskid());
		logManager.creatTaskLog(tlm, logger);
		
		return new ResponseWrapTo(CodeType.success, "已设置为客户端可见", null).toJson();
	}
	
	/**
	 * 
		 * @description	终止任务
		 * @author  han1088
		 * @param taskid
		 * @param cancercause
		 * @param constraint是否强制停止
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "stopHotelTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String stopHotelTask(String taskid, String cancercause, Integer constraint){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		String host = RequestUtil.getRequest().getRemoteHost();
		Map<String, Object> reMap = taskService.stopTaskByHotel(taskid,cancercause,constraint,user.getRealname());
		int code = (int) reMap.get("code");
		String message =  reMap.get("message").toString();
		if(code == 0){//取消成功
			Logger logger = new Logger(new Date(), userid, host,user.getRealname());
			String context = "终止任务";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_STOP);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
		}
		return new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 
		 * @description	取消任务
		 * @author  han1088
		 * @param taskid
		 * @param cancercause
		 * @param constraint
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancerHotelTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String cancerHotelTask(String taskid, String cancercause){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		String host = RequestUtil.getRequest().getRemoteHost();
		
		cancercause = (cancercause == null||cancercause.isEmpty())?"系统取消":cancercause;
		
		Map<String, Object> reMap = taskService.cancerTaskByHotel(taskid,cancercause,"3="+user.getUserid());
		int code = (int) reMap.get("code");
		String message =  reMap.get("message").toString();
		if(code == 0){//取消成功
			Logger logger = new Logger(new Date(), userid, host,user.getRealname());
			String context = "取消任务";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_CANCE);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
		}
		return new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 
		 * @description	取消帮工
		 * @author  han1088
		 * @param emid
		 * @param taskid
		 * @param cancercause
		 * @param constraint 1是，非1否
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancerEmTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String cancerEmTask(String emid,String taskid, String cancercause, Integer constraint){
		cancercause = "系统取消";
		Map<String, Object> reMap = taskService.cancerEmTaskByManager(emid,taskid,cancercause,constraint);
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		int code = (int) reMap.get("code");
		String message =  reMap.get("message").toString();
		if(code == 0){
			Employee em = employeeService.getEmployee(emid);
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), emid, host,user.getRealname());
			String context = "取消帮工:"+ em.getRealname();
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_CANCE);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
		}else if(code == 1){
			Employee em = employeeService.getEmployee(emid);
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), emid, host,user.getRealname());
			String context = "终止帮工:"+ em.getRealname();
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_CANCE);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
			code = 0;
		}
		return new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @param startDate
		 * @param endDate
		 * @param state
		 * @param sortType
		 * @param areaCode
		 * @param condition
		 * @param emInfo 帮工信息（名称，电话号码）
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskList", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getTaskList(String startDate, String endDate,Integer state, Integer sortType
			, Integer areaCode, String condition,Integer pageNo, String emInfo){
		Pager data = taskService.findHotelTaskByPage(startDate, endDate, state, areaCode, condition, pageNo, emInfo);
		List <Task> li = data.getList();
		if(sortType != null && sortType>0){
			if(sortType == 1){//按照时间升序
				ListSortUtil<Task> sort = new ListSortUtil<Task>();
				sort.sort(li, "creattime", true);
			}
			if(sortType == 2){//按照时间升序
				ListSortUtil<Task> sort = new ListSortUtil<Task>();
				sort.sort(li, "creattime", false);
			}
		}
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "addTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String addTask(Task task){
		String remark = task.getRemark();
		if(remark != null){
			task.setRemark(StrUtil.getSubString(remark,280));
		}
		String host = RequestUtil.getRequest().getRemoteHost();
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		if(task.getHotelid() == null){//还未绑定酒店
			return new ResponseWrapTo(-4, "请选择酒店", null).toJson();
		}
		Hotel h = hotelService.getHotelById(task.getHotelid());
		if(h.getState().intValue() != Constant.HOTEL_STATE_PASS.intValue()){
			return new ResponseWrapTo(-4, "酒店还未通过审核或者已经下架", null).toJson();
		}
		
		//task.setPublisher(h.getUserid());//发布人(对应酒店的酒店管家)
		
		if(DateUtil.daysDistance(task.getStarttime(),task.getEndtime())<0){
			return new ResponseWrapTo(-4, "任务起始时间必须早于结束时间", null).toJson();
		}
		
		if(DateUtil.daysDistance(new Date(),task.getStarttime()) <= 0){
			return new ResponseWrapTo(-3, "日期选择错误，请选择今天以后的日期作为开始时间", null).toJson();
		}
		
		task.setShowapp(Constant.APP_SHOW_CLOSE);//客户端不可见
		if(StringUtils.isBlank(task.getWelfare())){//福利
			task.setWelfare(h.getWelfare());
		}
		Map<String, Object> reMap = taskService.publicTask(task, Constant.USER_TYPE_PLATFORM);
		int code = (int) reMap.get("code");
		String message =  reMap.get("message").toString();
		if(code == 0){//发布成功
			Logger logger = new Logger(new Date(), userid, host,user.getRealname());
			String context = "发布任务";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_PUBLIC);
			tlm.setTaskid(task.getTaskid());
			logManager.creatTaskLog(tlm, logger);
		}
		return new ResponseWrapTo(code, message, task.getTaskid()).toJson();
	}
	
	/**
	 * 
		 * @description	获取任务详情
		 * @author  han1088
		 * @param taskid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskDetail(String taskid){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		
		Task task = taskService.getHotelTaskDteail(taskid);
		if(task == null){
			return new ResponseWrapTo(-1, "任务不存在", null).toJson();
		}
		
		SysUserHotel sh = sysUserHotelService.getBindHotelByUidHid(userid, task.getHotelid());
		if(sh == null){
			return new ResponseWrapTo(401, "你没有权限查看该酒店的任务详情", null).toJson();
		}
		
		List<Emtask>emtli = emTaskService.getEmTaskByTakid(taskid);
		Hotel hotel = hotelService.getHotelById(task.getHotelid());
		
		String tel = "";
		String realname = "";
		if(StringUtils.isNotBlank(task.getTel())){
			tel=task.getTel();
			realname = task.getRealname();
		}else{
			Hotelmanager hm = hotelmanagerService.findByUserid(task.getPublisher());
			if(hm == null){//可能是后台人员发布的订单
				user = systemuserService.findUserByUserid(task.getPublisher());
				if(user != null){
					tel=user.getTel();
					realname = user.getRealname();
				}else{
					System.out.println(task.getPublisher());
				}
			}else{
				tel=hm.getTel();
				realname = hm.getRealname();
			}
		}
		hotel.setRealname(realname);
		hotel.setTel(tel);
		
		if(emtli.size()>0){
			task.setIsedit(2);//不能被编辑
		}else{
			task.setIsedit(1);//可以被编辑
		}
		task.setNowdatetime(new Date());
		task.setAreaModel(AreaHelp.getInstance().getAreaModels(hotel.getArea().toString()));
		String taskJS = JSONObject.toJSONString(task,SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullStringAsEmpty);
		JSONObject js = JSONObject.parseObject(taskJS);
		
		js.put("hotel", hotel);
		//报名的帮工
		JSONArray jsarray = new JSONArray();
		for(Emtask emt : emtli){
			//查询服务的历史纪录
			List<Emtask> li = emTaskService.getEmTaskByHotelid(emt.getEmid(),emt.getHotelid());
			JSONObject emjs = new JSONObject();
			emjs.put("id", emt.getStringEmid());
			emjs.put("realname", emt.getRealname());
			emjs.put("tel", emt.getTel());
			if(emt.getIsstop() != null && emt.getIsstop().intValue() == 1){
				emjs.put("state", 7);//已终止
			}else{
				emjs.put("state", 5);//已报名显示取消按钮
			}
			emjs.put("area", emt.getArea());
			emjs.put("servercount", li.size());
			if(emt.getArea() != null){
				emjs.put("areaModel",AreaHelp.getInstance().getAreaModels(emt.getArea()));
			}else{
				emjs.put("areaModel","[]");
			}
			jsarray.add(emjs);
		}
		js.put("employeers", jsarray);
		
		//流转记录
		List<Logger> taskLogLi = logManager.getTaskLogInfoByTaskId(task.getTaskid());
		JSONArray jarr = new JSONArray();
		for(Logger loger : taskLogLi){
			String context = loger.getContext();
			context = JSONObject.parseObject(context).getString("context");
			JSONObject logjs = new JSONObject();
			logjs.put("context", context);
			logjs.put("creattime",loger.getCreattime());
			logjs.put("realname",loger.getRealname());
			jarr.add(logjs);
		}
		js.put("logger", jarr);
		return new ResponseWrapTo(CodeType.success, "", js).toJson();
	}
	
	/**
	 * 获取可以接单的帮工列表
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "searchEmployee", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String searchEmployee(String taskid, Integer areaCode, String condition, Integer pageNo){
		short pageSize = 20;
		Pager<Employee> data;
		Map<String, Object> dataMap = employeeService.searchEmployee(taskid, areaCode,condition,pageNo, pageSize); 
		int code = (int) dataMap.get("code");
		String message = (String) dataMap.get("message");
		if(code == 0){
			data = (Pager<Employee>) dataMap.get("eli");
			return new ResponseWrapTo(code, message,data).toJson();
		}else{
			return new ResponseWrapTo(code, message, null).toJson();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "addEmTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET, })
	public String addEmTask(String taskid, String emids){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		
		JSONArray emidsjarray = JSONArray.parseArray(emids);
		List<Employee> realnameLi = new ArrayList<Employee>();
		int i=0;
		Task t = taskService.getHotelTaskDteail(taskid);
		Hotel h = hotelService.getHotelById(t.getHotelid());
		/*if(t.getShowapp().intValue() == Constant.APP_SHOW_CLOSE){//还未确认发布
			return new ResponseWrapTo(-2, "该任务还未确认发布不能添加帮工", null).toJson();
		}*/
		int count = emTaskService.getEmTaskByTakid(t.getTaskid()).size();//获取已经报名的帮工
		for(Object js : emidsjarray){
			String emid = JSONObject.parseObject(js.toString()).getString("userid");
			int re = emTaskService.isAcceptTask(emid,taskid);
			/*if(emidsjarray.size() > t.getUsercount().intValue()){
				return new ResponseWrapTo(-1, "帮工人数超额，请重新选择", null).toJson();
			}
			if(t.getEmenroll() == t.getUsercount().intValue()){
				return new ResponseWrapTo(-2, "人数已满", null).toJson();
			}*/
			Employee em = employeeService.getEmployee(emid);
			if(re == 5){//已经报名
				continue;
			}else if(re == 7){//重新接单
				Emtask emtold = emTaskService.getEmTask(taskid, emid);
				emtold.setCanceltime(null);
				emtold.setIsstop(null);
				emtold.setCancercause(emtold.getCancercause()+"；帮工重新接单了");
				emTaskService.update(emtold);
				if(!StrUtil.isNullOrEmpty(em.getPushkey())){
					JSONObject reqparam = new JSONObject();
					reqparam.put("taskId", taskid);
					AppEmployyePushUtil.pushMessage(em.getPushkey(), 
						"【有人有活】", "您好，系统已为您分配"+h.getHotelname()
						+ "清洁任务（任务号"+taskid+")，点击查看详情。", "pageOrderDetail", reqparam);
				}
				realnameLi.add(em);
			}else if(re == -3 || re == 0 || re == 6){//没有报名过该任务
				//创建帮工任务
				Emtask emt = new Emtask();
				emt.setCreattime(new Date());
				emt.setEmid(emid);
				emt.setEndtime(t.getEndtime());
				emt.setHotelid(t.getHotelid());
				float reward = t.getUnitprice() * t.getLowestroom()
						*DateUtil.daysDistance(t.getStarttime(),t.getEndtime());
				emt.setReward(reward);
				emt.setStarttime(t.getStarttime());
				emt.setTaskid(t.getTaskid());
				emt.setUnitprice(t.getEmunitprice());//帮工单价
				emTaskService.save(emt);
				if(!StrUtil.isNullOrEmpty(em.getPushkey())){
					JSONObject reqparam = new JSONObject();
					reqparam.put("taskId", taskid);
					AppEmployyePushUtil.pushMessage(em.getPushkey(), 
						"【有人有活】", "您好，系统已为您分配"+h.getHotelname()
						+ "清洁任务（任务号"+taskid+")，点击查看详情。", "pageOrderDetail", reqparam);
				}
				try {
					//发送短信通知帮工
					MsgHelp.sendAddEmTask(em.getTel(), em.getRealname(),h.getHotelname(), taskid,DateUtil.formatYMD(emt.getStarttime())
							, DateUtil.formatYMD(emt.getEndtime()));
				} catch (ClientException e) {
					e.printStackTrace();
				}
				realnameLi.add(em);
				i++;
				//报名已满修改订单状态为待服务
				if(t.getUsercount().intValue() <= (i+count) && t.getState().intValue() == Constant.TASK_STATE_CREAT){
					t.setState(Constant.TASK_STATE_WAITSERVICE);
					taskService.update(t);
					break;
				}
			}
		}
		//记录日志
		String host = RequestUtil.getRequest().getRemoteHost();
		Logger logger = new Logger(new Date(), userid, host,user.getRealname());
		String context = "添加帮工:";
		for(Employee em:realnameLi){
			context = context+em.getRealname()+",";
			if(t.getState().intValue() == Constant.TASK_STATE_INSERVICE.intValue()){//服务中的订单中途加入帮工需要创建当天的考勤
				Childtask ct = childTaskService.getTaskAttendance(taskid, DateUtil.formatYMD(new Date()), em.getUserid());
				if(ct == null){//没有当日房量的
					ct = new Childtask();
					ct.setCreattime(new Date());
					ct.setEmid(em.getUserid());
					ct.setRealname(em.getRealname());
					ct.setResult(Constant.ATTENDANCE_NO_SUBMIMT);
					ct.setReward(0f);//单价*最低房量（实际的按结算）初始定位0
					ct.setCostmoney(0f);//酒店花费
					ct.setRoomcount(0f);//初始设定0个房间
					ct.setTaskid(t.getTaskid());
					childTaskService.save(ct);
				}
			}
		}
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_ADDEM);
		tlm.setTaskid(taskid);
		logManager.creatTaskLog(tlm, logger);
		return new ResponseWrapTo(0, "添加帮工成功", null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "exportTaskExcel", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public void exportTaskExcel(HttpServletResponse resp,HttpServletRequest req,String startDate, String endDate,Integer state, Integer sortType
			, Integer areaCode, String condition){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		//记录导出日志
		String host = RequestUtil.getRequest().getRemoteHost();
		Logger logger = new Logger(new Date(), user.getUserid(), host,user.getRealname());
		String context = "导出任务列表";
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_EXPORT);
		logManager.creatTaskLog(tlm, logger);
		
		List<Task> data = taskService.exportHotelTask(startDate, endDate, state, areaCode, condition);
		if(sortType != null && sortType>0){
			if(sortType == 1){//按照时间升序
				ListSortUtil<Task> sort = new ListSortUtil<Task>();
				sort.sort(data, "creattime", true);
			}
			if(sortType == 2){//按照时间升序
				ListSortUtil<Task> sort = new ListSortUtil<Task>();
				sort.sort(data, "creattime", false);
			}
		}
		String filename = "任务列表.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			HssfUtil.writeTaskHssf("任务列表", data, filename, resp.getOutputStream());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskCountGroupDate", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public String getTaskCountGroupDate(){
		Map<String, Integer> data = taskService.getTaskCount();
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	private String getLogContext(Task t){
		String context = "服务日期"+DateUtil.formatYMD(t.getStarttime())+"至"+DateUtil.formatYMD(t.getEndtime())
				+"帮工数量"+t.getUsercount()+"人";
		t.getWelfare();
		List<Object> data = JSONArray.parseArray(t.getWelfare());
		StringBuffer info = new StringBuffer("");
		for(Object o:data){
			JSONObject json = JSONObject.parseObject(o.toString());
			int id = json.getIntValue("id");
			int value = json.getIntValue("value");
			if(id == 1){//
				info.append("包吃"+value+"餐;");
			}else if(id == 2){
				if(value == 1){
					info.append("包住;");
				}else {
					info.append("不包住;");
				}
			}else if(id == 3){
				info.append("交通补贴:"+value+"元");
			}
		}
		context = context+info.toString()+";备注:"+t.getRemark();
		return context;
	}
	
	/**
	 * 修改还未确认考勤的房量
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "editChildTaskRoomCount", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public String editChildTaskRoomCount(Integer id,String roomDetail){
		Childtask ct = childTaskService.findChildTaskById(id);
		if(ct == null){
			return new ResponseWrapTo(CodeType.fail, "未能查询到对应考勤数据", null).toJson();
		}
		if(ct.getResult().intValue() != Constant.ATTENDANCE_SUBMIMT
				&& ct.getResult().intValue() != Constant.ATTENDANCE_NO_SUBMIMT){
			return new ResponseWrapTo(CodeType.fail, "已经确认的考勤不能修改", null).toJson();
		}
		
		childTaskService.editTaskAttendance(id,roomDetail);
		return new ResponseWrapTo(CodeType.success, "修改成功", null).toJson();
		
	}
}
